package com.aididi.jichu;

/**
 * @Auther: xuzexiang
 * @Date: 2018-11-6 0006 20:17
 * @Description:    cvs转html
 */
public class Main {
    /**
     * 过滤一些特殊字符
     *
     * @param lineIn
     * @return
     */
    public static String escapeChars(String lineIn) {
        StringBuilder sb = new StringBuilder();
        int lineLength = lineIn.length();
        for (int i = 0; i < lineLength; i++) {
            char c = lineIn.charAt(i);
            switch (c) {
                case '"':
                    sb.append("&quot;");
                    break;
                case '&':
                    sb.append("&amp;");
                    break;
                case '\'':
                    sb.append("&apos;");
                    break;
                case '<':
                    sb.append("&lt;");
                    break;
                case '>':
                    sb.append("&gt;");
                    break;
                default:
                    sb.append(c);
            }
        }
        return sb.toString();
    }
    public static void buildRow(StringBuilder sb, String[] columns) {
        sb.append("<tr>");
        for (int i = 0; i < columns.length; i++) {
            sb.append("<th>");
            sb.append(escapeChars(columns[i]));
            sb.append("</th>");
        }
        sb.append("</tr>\n");
    }
    public static void main(String[] args) throws Exception {
        String csv =
                "角色,描述\n" +
                        "牛妹,牛客大网红，著有<牛客网发帖十大规范&&准则>\n" +
                        "牛牛,牛客小网红，长期出现在牛客编程题里，智商保持在1 + 1 = 3\n" +
                        "狗哥,牛客待嫁小青年";
        String[] lines = csv.split("\n");
        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
        sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
        sb.append("<head><meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\"/>\n");
        sb.append("<title>CSV2HTML</title>\n");
        sb.append("<style type=\"text/css\">");
        sb.append("body{background-color:#FFF;color:#000;font-family:OpenSans,sans-serif;font-size:10px;}");
        sb.append("table{border:0.2em solid #2F6FAB;border-collapse:collapse;}");
        sb.append("th{border:0.15em solid #2F6FAB;padding:0.5em;background-color:#E9E9E9;}");
        sb.append("td{border:0.1em solid #2F6FAB;padding:0.5em;background-color:#F9F9F9;}</style>");
        sb.append("</head><body><h1>CSV2HTML</h1>\n");
        sb.append("<table>\n");
        for (String line : lines) {
            String[] columns = line.split(",");
            buildRow(sb, columns);
        }
        sb.append("</table></body></html>");
        System.out.print(sb.toString());
    }
}
